<?php

namespace Behavior;

class IpBehavior {

    public function run(&$params){
		$cityid=session('CityId');
		if(C('otoo_open') && empty($cityid)){
			$this->SetIPAPI();
		}else{
			$cityarr=session('City');
			if(empty($_GET['city']) && !empty($cityarr['catid'])){
				$_GET['city']=$cityarr['catid'];
			}
		}
    }
	
	//IP
	function SetIPAPI(){
		
		$ip=GetClientIp();

		$url ="http://api.map.baidu.com/location/ip?ak=%s&ip=%s&coor=%s&sn=%s";
		$ak=C('baidu_ip_accesskey');
		$uri='/location/ip/';
		$coor='bd09ll';
		
		$queryarray = array (
			'ak' =>$ak,
			'ip' =>$ip,
			'coor'=>$coor
		);
		 
		$json=CurlGetContent('GET',sprintf($url,$ak,$ip,$coor,$this->caculateAKSN($ak, $sk, $uri,$queryarray)));
		$address=json_decode($json);

		$citycode=0; //默认全国
		$pointx=0; //坐标x
		$pointy=0; //坐标y
		if(!empty($address)){
			$citycode=intval($address->content->address_detail->city_code);
			$pointx=$address->content->point->x;
			$pointy=$address->content->point->y;
		}
		
		if($citycode){

			$cityarr=M('CategoryCity')->where(" apiid=$citycode ")->find();
			if(!empty($cityarr['catid'])){
				session('City',$cityarr);
				if(empty($_GET['city'])){
					$_GET['city']=$cityarr['catid'];
				}
			}
			session('CityId',$citycode);
			
		}
		
		if($pointx || $pointy){
			session('PointX',$pointx);
			session('PointY',$pointy);
		}
	}
	
	function ChangePosition($location){

		$url ="http://api.map.baidu.com/geocoder/v2/?ak=%s&location=%s&output=%s&sn=%s";
		$ak=C('baidu_ip_accesskey');
		$uri='/geocoder/v2/';
		$output='json';
		
		$queryarray = array (
			'ak' =>$ak,
			'location' =>$location,
			'output'=>$output
		);
		 
		$json=CurlGetContent('GET',sprintf($url,$ak,$location,$output,$this->caculateAKSN($ak, $sk, $uri,$queryarray)));
		return json_decode($json);
	}
	
	function caculateAKSN($ak,$sk,$url,$queryarray,$method = 'GET'){  
		if($method === 'POST'){  
			ksort($queryarray);  
		}  
		$querystring = http_build_query($queryarray);  
		return md5(urlencode($url.'?'.$querystring.$sk));  
	}
}
